#include "init.h"
#include "comm/boot_info.h"
#include "cpu/cpu.h"
#include "cpu/irq.h"
#include "dev/time.h"
#include "tools/log.h"
#include "os_cfg.h"
#include "tools/klib.h"
#include "core/task.h"
#include "tools/list.h"
#include "ipc/semaphore.h"
#include "core/memory.h"
#include "dev/console.h"
#include "dev/kbd.h"
#include "fs/fs.h"

void kernel_init(boot_info_t *boot_info)
{ 
    ASSERT(boot_info->ram_region_count != 0);
    // gdt表初始化
    cpu_init();
    // idt表初始化、安装实际异常处理程序
    irq_init();

    // 日志输出初始化
    log_init();
    // 内存初始化
    memory_init(boot_info);
    //文件系统初始化
    fs_init();
    // 安装时间片中断处理程序
    time_init();
    // 任务管理器初始化
    task_manager_init();
}

void goto_first_task(void)
{
    task_t * curr_task = curr_task_get();
    ASSERT(curr_task != 0);

    tss_t * curr_tss = &(curr_task->tss);
    // 此处跳转到first task，同时使用iret切换first task特权级
    __asm__ __volatile__(
        "push %[ss]\n\t"
        "push %[esp]\n\t"
        "push %[eflags]\n\t"
        "push %[cs]\n\t"
        "push %[eip]\n\t"
        "iret"::[ss]"r"(curr_tss->ss),[esp]"r"(curr_tss->esp),
        [eflags]"r"(curr_tss->eflags),[cs]"r"(curr_tss->cs),
        [eip]"r"(curr_tss->eip)
    );
}

void init_main(void)
{
    log_printf("============================================");
    log_printf("kernel is running......");
    log_printf("This is %s's OS. x86-based, %d bit",OS_AUTHOR, OS_NUM_SIZE);
    log_printf("OS version : %s");
    log_printf("============================================");
    first_task_init(); 
    goto_first_task();  
}

